import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'map_root.dart';

class ChinaMap extends StatefulWidget {
  const ChinaMap({super.key});

  @override
  State<ChinaMap> createState() => _ChinaMapState();
}

class _ChinaMapState extends State<ChinaMap> {
  final String url =
      'https://geo.datav.aliyun.com/areas_v2/bound/100000_full.json'; //全国点位详细信息

  // 请求点位信息
  Future<MapRoot?> getMapRoot() async {
    try {
      final Response response = await Dio().get(url);
      print("response=${response.data}");
      if (response.data != null) {
        var data = MapRoot.fromJson(response.data);
        print("response2=$data");
        return data;
      } else {
        return null;
      }
    } catch (e) {
      print(e);
      return null;
    }
  }

  late Future<MapRoot?> _future;

  @override
  void initState() {
    super.initState();
    _future = getMapRoot();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _future,
        builder: (context, async) {
          print(async.data);
          if (async.data != null) {
            return CustomPaint(
              size: const Size(500, 400),
              painter: MapPainter(mapRoot: async.data),
            );
          } else {
            return const CupertinoActivityIndicator();
          }
        });
  }
}

class MapPainter extends CustomPainter {
  final MapRoot? mapRoot;

  MapPainter({required this.mapRoot});

  final Paint _paint = Paint()
    ..strokeWidth = 0.1
    ..isAntiAlias = true;
  final List<Color> colors = [
    Colors.red,
    Colors.yellow,
    Colors.blue,
    Colors.green
  ];
  int colorIndex = 0;

  @override
  void paint(Canvas canvas, Size size) {
    if (mapRoot == null) return;
    if (mapRoot?.features == null) return;

    canvas.clipRect(
        Rect.fromPoints(Offset.zero, Offset(size.width, size.height)));
    canvas.translate(size.width / 2, size.height / 2);

    var coordinate = mapRoot!.features![0]?.geometry?.coordinates[0][0][0];
    double dx = coordinate?.dx ?? 0;
    double dy = coordinate?.dy ?? 0;
    canvas.translate(-dx, -dy);

    double rate = 0.65;

    canvas.translate(-700 * rate, 350 * rate);
    canvas.scale(8 * rate, -10.5 * rate);

    _drawMap(canvas, size);
  }

  void _drawMap(Canvas canvas, Size size) {
    // 全国省份循环
    for (int i = 0; i < mapRoot!.features!.length; i++) {
      var feature = mapRoot!.features![i];
      if (feature == null) return;
      PaintingStyle style;
      Color color;
      Path path = Path();
      if (feature.properties?.name == '台湾省' ||
          feature.properties?.name == "海南省" ||
          feature.properties?.name == "河北省" ||
          feature.properties?.name == "") {
        // 海南和台湾和九段线
        feature.geometry?.coordinates.forEach((List<List<Offset>> lv3) {
          for (var lv2 in lv3) {
            for (var lv1 in lv2) {
              path.lineTo(lv1.dx, lv1.dy); // 优化一半点位
            }
          }
        });

        if (feature.properties?.name == "") {
          style = PaintingStyle.stroke;
          color = Colors.black;
        } else {
          style = PaintingStyle.fill;
          color = colors[colorIndex % 4];
          colorIndex++;
        }
      } else {
        final Offset first =
            feature.geometry?.coordinates[0][0][0] ?? Offset.zero;
        path.moveTo(first.dx, first.dy);
        if (feature.geometry == null) return;
        style = PaintingStyle.fill;
        color = colors[colorIndex % 4];
        colorIndex++;
      }

      canvas.drawPath(
          path,
          _paint
            ..color = color
            ..style = style); // 绘制地图
    }
  }

  @override
  bool shouldRepaint(covariant MapPainter oldDelegate) =>
      oldDelegate.mapRoot != mapRoot;
}
